package controller

import (
	"YingShop/entity"
	querystruct "YingShop/queryStruct"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ProductCategoryController struct {
	Result
}

func (categoryController ProductCategoryController) Get(ctx *gin.Context) {
	categoryId, _ := strconv.Atoi(ctx.Param("categoryId"))
	productCategory := entity.ProductCategory{CategoryId: categoryId}
	err := productCategory.Load()
	if err != nil {
		categoryController.RetCode = -1
		categoryController.Msg = err.Error()
	} else {
		categoryController.RetCode = 0
		categoryController.Msg = "success"
		categoryController.Data = gin.H{
			"categoryId":   productCategory.CategoryId,
			"categoryName": productCategory.CategoryName,
		}
	}
	ctx.JSON(200, categoryController.Result)
}

func (categoryController ProductCategoryController) Post(ctx *gin.Context) {
	categoryParam := querystruct.CategoryPostParam{}
	if err := ctx.ShouldBindJSON(&categoryParam); err != nil {
		categoryController.RetCode = -1
		categoryController.Msg = err.Error()
		ctx.JSON(200, categoryController.Result)
		return
	}
	userName, _ := ctx.Keys["userName"].(string)
	categoryEntity := entity.ProductCategory{CategoryName: categoryParam.CategoryName, Creator: userName, Modifier: userName}
	err := categoryEntity.Add()
	if err != nil {
		categoryController.RetCode = -1
		categoryController.Msg = err.Error()
		ctx.JSON(200, categoryController.Result)
		return
	}
	categoryController.RetCode = 0
	categoryController.Msg = "success"
	categoryController.Data = gin.H{
		"categoryId": categoryEntity.CategoryId,
	}
	ctx.JSON(200, categoryController.Result)
}

func (categoryController ProductCategoryController) GetAllCategory(ctx *gin.Context) {
	categoryList := entity.ProductCategoryList{}
	categoryList.GetAllCategory()
	categoryController.RetCode = 0
	categoryController.Msg = "success"
	categoryController.Data = gin.H{
		"categoryList": categoryList.CategoryList,
	}
	ctx.JSON(200, categoryController.Result)

}
